import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../../Services/api_service.dart';
import '../../base/base_widget.dart';
import '../../model/article_model.dart';

import '../web/web_page.dart';
import 'banner.dart';
import 'package:fluttertoast/fluttertoast.dart';

// ignore: must_be_immutable
class HomePage extends BaseWidget {
  HomePage({super.key});

  @override
  BaseWidgetState<BaseWidget> getState() {
    return HomePageState();
  }
}

class HomePageState extends BaseWidgetState<HomePage> {
  final List<ArticleModel> _articleList = [];
  final ScrollController _scrollController = ScrollController();
  bool showToTopBtn = false; //是否显示“返回到顶部”按钮
  int _page = 0;

  @override
  void initState() {
    super.initState();

    setAppBarVisible(false);

    getData();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getMore();
      }

      //当前位置是否超过屏幕高度
      if (_scrollController.offset < 200 && showToTopBtn) {
        setState(() {
          showToTopBtn = false;
        });
      } else if (_scrollController.offset >= 200 && showToTopBtn == false) {
        setState(() {
          showToTopBtn = true;
        });
      }
    });
  }

  //获取文章列表数据
  Future<Null> getData() async {
    _page = 0;
    ApiService().getArticleList(_page, (List<ArticleModel> articleList) {
      if (articleList.isNotEmpty) {
        showContent();
        setState(() {
          _articleList.clear();
          _articleList.addAll(articleList);
        });
      } else {
        showEmpty();
      }
    }, (DioError error) {
      setState(() {
        showError();
      });
    });
  }

  //加载更多的数据
  Future<Null> _getMore() async {
    _page++;
    ApiService().getArticleList(_page, (List<ArticleModel> articleList) {
      if (articleList.isNotEmpty) {
        showContent();
        setState(() {
          _articleList.addAll(articleList);
        });
      } else {
        Fluttertoast.showToast(msg: "没有更多数据了");
      }
    }, (DioError error) {
      //发生错误
      setState(() {
        showError();
      });
    });
  }

  @override
  AppBar getAppBar() {
    return AppBar(
      title: const Text("不显示"),
    );
  }

  @override
  Widget getContentWidget(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        displacement: 15,
        onRefresh: getData,
        child: ListView.separated(
            itemBuilder: _renderRow,
            physics: const AlwaysScrollableScrollPhysics(),
            separatorBuilder: (BuildContext context, int index) {
              return Container(
                height: 0.5,
                color: Colors.black26,
              );
            },
            controller: _scrollController,
            //包含轮播图和加载更多
            itemCount: _articleList.length + 2),
      ),
      floatingActionButton: !showToTopBtn
          ? null
          : FloatingActionButton(
          child: const Icon(Icons.arrow_upward),
          onPressed: () {
            //返回到顶部时执行动画
            _scrollController.animateTo(.0,
                duration: const Duration(milliseconds: 200), curve: Curves.ease);
          }),
    );
  }

  Widget? _renderRow(BuildContext context, int index) {
    if (index == 0) {
      return Container(
        height: 200,
        color: Colors.white,
        child: const BannerWidget(),
      );
    }

    if (index < _articleList.length - 1) {
      return InkWell(
        onTap: ()  {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return WebViewPage(
                title: _articleList[index - 1].title, url: _articleList[index - 1].link);
          }));

        },
        child: Column(
          children: <Widget>[
            Container(
              color: Colors.white,
              padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
              child: Row(
                children: <Widget>[
                  Text(
                    _articleList[index - 1].author,
                    style: const TextStyle(fontSize: 12),
                    textAlign: TextAlign.left,
                  ),
                  Expanded(
                    child: Text(
                      _articleList[index - 1].niceDate,
                      style: const TextStyle(fontSize: 12),
                      textAlign: TextAlign.right,
                    ),
                  ),
                ],
              ),
            ),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      _articleList[index - 1].title,
                      maxLines: 2,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                        color: Color(0xFF3D4E5F),
                      ),
                      textAlign: TextAlign.left,
                    ),
                  )
                ],
              ),
            ),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: Text(
                      _articleList[index - 1].superChapterName,
                      style: const TextStyle(fontSize: 12),
                      textAlign: TextAlign.left,
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      );
    }
    return null;
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  bool get wantKeepAlive => true;

  @override
  void onClickErrorWidget() {
    showLoading();
    getData();
  }
}